#!/usr/bin/env python3
"""
BoLe HR Platform Setup Script
Automated setup and configuration for the intelligent HR multi-agent platform
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path
import asyncio

def print_header(title):
    """Print a formatted header"""
    print(f"\n{'='*60}")
    print(f"🚀 {title}")
    print('='*60)

def print_step(step):
    """Print a step"""
    print(f"\n📋 {step}...")

def print_success(message):
    """Print success message"""
    print(f"✅ {message}")

def print_error(message):
    """Print error message"""
    print(f"❌ {message}")

def print_warning(message):
    """Print warning message"""
    print(f"⚠️  {message}")

def run_command(command, description="", check=True):
    """Run a shell command"""
    print(f"   Running: {command}")
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, check=check)
        if result.stdout:
            print(f"   Output: {result.stdout.strip()}")
        return True
    except subprocess.CalledProcessError as e:
        print_error(f"Command failed: {e}")
        if e.stderr:
            print(f"   Error: {e.stderr.strip()}")
        return False

def create_directories():
    """Create necessary directories"""
    print_step("Creating directory structure")
    
    directories = [
        "data/vector_db",
        "data/graph_db", 
        "data/processed",
        "data/raw",
        "logs",
        "tests/data"
    ]
    
    for directory in directories:
        Path(directory).mkdir(parents=True, exist_ok=True)
        print_success(f"Created directory: {directory}")

def setup_environment():
    """Setup environment file"""
    print_step("Setting up environment configuration")
    
    env_example = Path(".env.example")
    env_file = Path(".env")
    
    if env_example.exists() and not env_file.exists():
        shutil.copy(env_example, env_file)
        print_success("Created .env file from .env.example")
        print_warning("Please edit .env file with your actual API keys and configuration")
    elif env_file.exists():
        print_success(".env file already exists")
    else:
        print_error(".env.example file not found")
        return False
    
    return True

def install_dependencies():
    """Install Python dependencies"""
    print_step("Installing Python dependencies")
    
    # Install core dependencies first
    core_deps = [
        "fastapi", "uvicorn", "pydantic", "python-multipart", 
        "pandas", "numpy", "scikit-learn", "nltk",
        "pymupdf", "python-docx", "openpyxl", "beautifulsoup4"
    ]
    
    for dep in core_deps:
        success = run_command(f"pip install {dep}", f"Installing {dep}", check=False)
        if success:
            print_success(f"Installed {dep}")
        else:
            print_warning(f"Failed to install {dep}")
    
    # Try to install ChromaDB (might take time)
    print_step("Installing ChromaDB (this may take a while)")
    success = run_command("pip install chromadb", "Installing ChromaDB", check=False)
    if success:
        print_success("ChromaDB installed successfully")
    else:
        print_warning("ChromaDB installation failed - you may need to install manually")
    
    return True

def install_lightrag():
    """Install LightRAG from source"""
    print_step("Installing LightRAG from source")
    
    lightrag_dir = Path("/tmp/lightrag_source")
    if lightrag_dir.exists():
        success = run_command(f"cd {lightrag_dir} && pip install -e .", "Installing LightRAG", check=False)
        if success:
            print_success("LightRAG installed successfully")
        else:
            print_warning("LightRAG installation failed - continuing without it")
    else:
        print_warning("LightRAG source not found at /tmp/lightrag_source")
    
    return True

def test_basic_functionality():
    """Test basic system functionality"""
    print_step("Testing basic system functionality")
    
    # Run the simple test
    success = run_command("python simple_test.py", "Running basic tests", check=False)
    if success:
        print_success("Basic functionality tests passed")
    else:
        print_warning("Some basic tests failed - check the output above")
    
    return True

def create_sample_config():
    """Create sample configuration for testing"""
    print_step("Creating sample configuration for testing")
    
    sample_env = """# Sample configuration for testing (no real API keys)
OPENAI_API_KEY=sk-test-key-here
ANTHROPIC_API_KEY=test-key-here
NEO4J_PASSWORD=test-password
GITHUB_TOKEN=test-token
DEVELOPMENT_MODE=true
ENABLE_TEST_MODE=true
MOCK_EXTERNAL_APIS=true
"""
    
    test_env = Path(".env.test")
    if not test_env.exists():
        with open(test_env, 'w') as f:
            f.write(sample_env)
        print_success("Created .env.test file for testing")
    
    return True

def print_next_steps():
    """Print next steps for user"""
    print_header("Setup Complete! 🎉")
    
    print("\n📝 Next Steps:")
    print("1. Edit .env file with your actual API keys:")
    print("   - Add your OpenAI API key")
    print("   - Add your Anthropic API key (optional)")
    print("   - Configure database passwords")
    
    print("\n2. Start required services:")
    print("   - Neo4j database (for graph storage)")
    print("   - Redis (for caching, optional)")
    
    print("\n3. Test the system:")
    print("   python simple_test.py")
    
    print("\n4. Process some resumes:")
    print("   python main.py process-data data/resume_dataset/data/data/ACCOUNTANT")
    
    print("\n5. Start the API server:")
    print("   python main.py serve")
    
    print("\n6. Visit the API documentation:")
    print("   http://localhost:8000/docs")
    
    print("\n📚 Documentation:")
    print("   - Check README.md for detailed instructions")
    print("   - Review config/settings.yaml for advanced configuration")
    print("   - Explore the src/ directory for code structure")

def main():
    """Main setup function"""
    print_header("BoLe HR Platform Setup")
    print("This script will set up the intelligent HR multi-agent platform")
    
    try:
        # Check Python version
        if sys.version_info < (3, 8):
            print_error("Python 3.8 or higher is required")
            return False
        
        print_success(f"Python version: {sys.version}")
        
        # Setup steps
        steps = [
            create_directories,
            setup_environment,
            install_dependencies,
            install_lightrag,
            create_sample_config,
            test_basic_functionality
        ]
        
        for step in steps:
            try:
                step()
            except Exception as e:
                print_error(f"Step failed: {e}")
                print_warning("Continuing with remaining steps...")
        
        print_next_steps()
        return True
        
    except KeyboardInterrupt:
        print("\n\n⚠️  Setup interrupted by user")
        return False
    except Exception as e:
        print_error(f"Setup failed: {e}")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)